<template>
  <div class="container">
    <el-card class="table-container">
      <div style="margin: 0 10px 20px 10px">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="月份" prop="month">
            <el-col :span="22">
              <el-date-picker v-model="searchForm.month" type="month" placeholder="选择月">
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="状态" prop="auditStatus">
            <el-select v-model="searchForm.auditStatus" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleRest">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-if="roles.indexOf('bm_yuan') != -1" type="primary" @click="handleAdd">新增</el-button>
          </el-form-item>

        </el-form>
      </div>
      <el-table :data="tableData.list" row-key="id" v-loading="queryLoading"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column align="center" key="submitter" prop="submitter" label="提交人员" />
        <el-table-column align="center" key="submitTime" prop="submitTime" label="提交时间" />
        <el-table-column align="center" key="deptName" prop="deptName" label="所属部门" />
        <el-table-column align="center" key="auditor" prop="auditor" label="审核人员" />
        <el-table-column align="center" key="auditTime" prop="auditTime" label="审核时间" />
        <el-table-column align="center" key="auditStatus" prop="auditStatus" label="当前状态">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.auditStatus == '未审核'">未审核</el-tag>
            <el-tag type="success" v-if="scope.row.auditStatus == '审核通过'">审核通过</el-tag>
            <el-tag type="danger" v-if="scope.row.auditStatus == '审核驳回'">审核驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" key="minioLink" prop="minioLink" label="文件下载">
          <template slot-scope="scope">
            <el-link v-if="scope.row.auditStatus != '审核驳回'" type="primary"
              @click="handledownload(scope.row.minioLink, scope.row.fileName)"><i class="el-icon-link"></i> {{
                scope.row.fileName }}</el-link>
            <el-link type="info" v-else><i class="el-icon-link"></i> {{ scope.row.fileName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column align="center" key="rejectReason" prop="rejectReason" label="驳回原因">
          <template slot-scope="scope">
            <span style="color: #ff4949;">{{ scope.row.rejectReason }}</span>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" fixed="right" align="center" width="150">
          <template slot-scope="scope">
            <el-popconfirm @confirm="handleConfirm(scope.row.id)" @cancel="handleCancel(scope.row.id)"
              confirm-button-text='是' cancel-button-text='否' icon="el-icon-info" icon-color="red" title="是否审核通过">
              <el-button :disabled="!(roles.indexOf('bu_zhu') != -1 && scope.row.auditStatus == '未审核')" slot="reference"
                size="mini" title="审核" type="primary">
                <i class="fa fa-pencil" />
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页信息 -->
      <div class="pagination-container">
        <el-pagination background layout="total, prev, pager, next, jumper" @current-change="handlePageChange"
          @size-change="handleSizeChange" :current-page="pageNum" :total="tableData.total">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog :visible.sync="addAuditDialog" title="上传审核文件">
      <div style="display: flex;justify-content: center;">
        <el-upload class="upload-demo" ref="uploadFile" :limit="1" accept=".xlsx" drag :action="action" multiple
          :headers="headers" :before-upload="handleBefore" :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <div>
        <div v-if="errorData.data_mismatch && errorData.data_mismatch.length>0">
          <div style="font-size: 18px; font-weight: bold; color:#ff4949;">数据错误</div>
          <div>
            <p v-html="item" style="font-size: 16px;" v-for="item in  errorData.data_mismatch" :key="item">
             </p>
          </div>
        </div>
        <div v-if="errorData.header_mismatch && errorData.header_mismatch.length>0">
          <div style="font-size: 18px; font-weight: bold; color:#ff4949;">表头错误</div>
          <div>
             <p  v-html="item" v-for="item in  errorData.header_mismatch" :key="item">
             </p>
          </div>
        </div>
        <div v-if="errorData.key_not_found && errorData.key_not_found.length>0">
          <div style="font-size: 18px; font-weight: bold; color:#ff4949;">重复数据</div>
          <div>
            <p v-for="item in  errorData.key_not_found" :key="item">
              {{ item }}
             </p>
          </div>
        </div>
        <div v-if="errorData.sheet_missing && errorData.sheet_missing.length>0">
          <div style="font-size: 18px; font-weight: bold; color:#ff4949;">缺少sheet</div>
          <div>
            <p v-for="item in  errorData.sheet_missing" :key="item">
              {{ item }}
             </p>
          </div>
        </div>
      </div>
      <div class="button-container" style="text-align: center">
        <el-button type="primary" @click.native.prevent="handleAddAudit">提交审核</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="shenheDialog" title="文件审核">
      <el-form :inline="true" :model="shenheForm" class="demo-form-inline">
        <el-form-item label="营业厅" prop="parentId">
          <el-col :span="22">
            <el-input :rows="5" v-model="searchForm.name" clearable type="text" placeholder="请输入营业厅" />
          </el-col>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { Message, Loading } from 'element-ui'
import AuditApi from '../api/audit'
import { getToken } from '@/utils/auth'
import URL from '@/api/api'
import { parseTime } from '@/utils'
export default {
  name: 'auditList',
  data() {
    return {
      options: [

        {
          value: '未审核',
          label: '未审核'
        },
        {
          value: '审核通过',
          label: '审核通过'
        },
        {
          value: '审核驳回',
          label: '审核驳回'
        }
      ],
      /* 搜索请求数据*/
      searchForm: {
        month: "",
        auditStatus: ""
      },
      shenheForm: {
        month: ""
      },
      pageSize: 10,
      pageNum: 1,
      // 表格数据
      tableData: {
        list: [],
        total: 0,
      },
      mode: 'edit',
      // 是否显示添加/编辑对话框
      addAuditDialog: false,
      shenheDialog: false,
      // 当前处理行
      currentRecord: {
        id: undefined,
        parentId: undefined,
        orderId: undefined,
        name: undefined
      },
      queryLoading: false,
      exportLoading: false,
      autoWidth: true,
      bookType: 'xlsx',
      action: URL + "/excel/upload-Yan",
      headers: {
        Authorization: getToken(),
      },
      minioLink: "",
      originalFilename: "",
      loading: null,
      roles: this.$store.getters.roles,
      errorData: {}
    }
  },
  mounted() {
    this.init()

  },
  methods: {
    // 页面初始化
    init() {
      this.handleQuery()
    },
    handleQuery() {
      this.pageNum = 1
      this.query()
    },
    handleRest() {
      this.pageNum = 1
      this.searchForm.month = "",
        this.searchForm.auditStatus = ""
      this.query()
    },
    query() {
      return new Promise((resolve, reject) => {

        this.queryLoading = true
        if (this.searchForm.month) {
          this.searchForm.month = parseTime(this.searchForm.month, '{y}-{m}')
        }
        const param = Object.assign({}, this.searchForm)
        AuditApi
          .getAuditinfoList({ ...this.searchForm, pageSize: this.pageSize, pageNum: this.pageNum })
          .then(response => {
            const data = response.data
            if (data.code === 200) {
              const list = response.data.data.list
              this.tableData.list = list;
              this.tableData.total = data.data.total;
            } else {
              Message.error(data.message)
              reject()
            }
            this.queryLoading = false
          })
          .catch(error => {
            if (error.message !== '') {
              //Message.error(error.message)
            }
            this.queryLoading = false
            reject(error)
          })
      })
    },
    handleAddAudit() {
      if (!this.minioLink && !this.originalFilename) {
        return Message.error("审核文件不能为空")
      }
      AuditApi.addAuditinfo({ minioLink: this.minioLink, fileName: this.originalFilename }).then(res => {
        if (res.data.code == 200) {
          Message.success("提交成功")
          this.addAuditDialog = false
          this.query()
        }
      })
    },
    handleAdd() {
      this.addAuditDialog = true
      this.$nextTick(() => {
        this.$refs.uploadFile.clearFiles()
        this.errorData={}
      })
    },
    handleDetail(row) {
      this.shenheDialog = true
    },
    // 处理翻页事件
    handlePageChange(currentPage) {
      this.pageNum = currentPage
      this.query()
    },
    // 处理页面总条数事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.query()
    },
    // 处理对话框关闭事件
    handleDialogClose(done) {
      this.showEditDialog = false
      this.$refs.editForm.resetFields()
      done()
    },
    handleBefore() {
      this.loading = Loading.service({
        lock: true,
        text: '文件对比中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)'
      })
    },
    handleAvatarSuccess(resp) {
      this.loading.close()

      if (resp.data.code == 200) {
        this.minioLink = resp.data.objectName
        this.originalFilename = resp.data.originalFilename
        this.errorData={}
        Message.success("上传成功")

      } else {
        Message.error("审核不通过")
        this.minioLink = ''
        this.originalFilename =''
        this.errorData = resp.data
        this.$refs.uploadFile.clearFiles()
      }

    },
    handleAvatarError(error) {
      Message.error("模板上传失败，格式错误!")
      this.loading.close()
    },
    handledownload(filename, name) {
      AuditApi.downloadFile(filename ).then(res => {
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(res.data);
        a.href = url;
        a.download = name;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      })
    },
    handleConfirm(id) {
      console.log("审核通过")
      AuditApi.updateAudit({ id, auditStatus: "审核通过" }).then(res => {
        console.log(res)
        this.query()
        Message.success("审核成功")
      })
    },
    handleCancel(id) {

      this.$prompt('请输入原因', '驳回原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {

        AuditApi.updateAudit({ id, auditStatus: "审核驳回", rejectReason: value }).then(res => {
          console.log(res)
          this.query()
          Message.success("驳回成功")
        })
        console.log(value)
      }).catch(() => {

      });
    }
  }
}
</script>
<style>
.container {
  margin: 10px;
}

.table-container {
  margin-top: 0px;
}

.pagination-container {
  margin-top: 30px;
  text-align: right;
}
</style>
